/**
 * 选择人员插件
 * Created by wuwt on 2015/7/20.
 * 需要用到的js：ztree，select2，icheck
 * 使用说明：在需要弹出选择人员窗口的标签加上 onclick="checkUser_showModal('');"可以传入“管理员”或“学员”来进行查询，默认为空查询所有人员。
 * 确认选择人员按钮事件需要在使用的页面上实现如下方法:
     function checkUser_enter(){
        var checkUserIds = $("#checkUser_userIds").val();//选择的人员id字符串集合
        if(checkUserIds != ""){
            //根据id集合查询用户信息
            $.post(getUserListByIds_url,{"userIds":checkUserIds},function(data){
                var userList = data;
                var userInfo = userList[0];
                var userId = userInfo.userId;
                var loginName= userInfo.loginName;
                var userName = userInfo.userName;
                ...
            })
        }
        //关闭选择人员窗口
        checkUser_closeModal();
    }
 */
var checkUserPage_url = "/osm/controller/user/checkUserPage";//选择人员窗口页面请求地址(不能跨域)
var checkUserList_url = "/osm/controller/user/checkUserList";//查询人员列表请求地址
var getUserListByIds_url = "/osm/controller/user/getUserListByIds";//查询人员信息列表请求地址
var checkUserType = '';//选择人员类型：管理员，学员
$(function(){
    var div = '<div id="loadCheckUserDiv"></div>';
    $("body").append(div);
    checkUser_loadModal();
})

//加载选择人员窗体组件
function checkUser_loadModal(){
    $("#loadCheckUserDiv").load(checkUserPage_url,function(){
        $("#checkUser_post").select2({minimumResultsForSearch:Infinity});
        $("input[name='checkUser_checkAll']").iCheck({
            checkboxClass: "icheckbox_minimal-blue",
            radioClass: "iradio_minimal-blue",
            increaseArea: "20%"
        });
        $("input[name='checkUser_checkAll']").on("ifClicked", function(event){
            if(!$(this).prop("checked")){
                $("input[name='checkUser_checkUser']").iCheck("check");
                var checkUsers = $("input[name='checkUser_checkUser']:checked");
                var checkUserArray = $("#checkUser_userIds").val().split(",");
                var checkUserStr = '';
                $.each(checkUsers,function(i,checkUser){
                    var userId = $(checkUser).val();
                    if($.inArray(userId,checkUserArray) < 0){
                        checkUserArray.push(userId);
                        var userName = $(checkUser).attr("userName");
                        checkUserStr+='<span class="btn btn-default btn-xs" id="checkUser_'+userId+'" style="margin: 0px 5px 5px 0px;">'+userName+'<span aria-hidden="true" onclick=removeCheckUser("'+userId+'")>&nbsp;&times;</span></span>';
                    }
                });
                $("#checkUser_userIds").val(array_remove("",checkUserArray));
                $("#checkUser_area").append(checkUserStr);
            }else{
                $("input[name='checkUser_checkUser']").iCheck("uncheck");
                var uncheckUsers = $("input[name='checkUser_checkUser']").not("input:checked");
                $.each(uncheckUsers,function(i,checkUser){
                    var userId = $(checkUser).val();
                    removeCheckUser(userId);
                });
            }
        });
        //加载部门树形下拉菜单
        setDepartmentTreeMenu("checkUser_department");
    });
}

//打开选择人员窗口
function checkUser_showModal(userType){
    checkUserType = userType==undefined?"":userType;
    $("#checkUser_modal").modal("show");
    checkUser_getList(1);
}

//关闭选择人员窗口
function checkUser_closeModal(){
    $("#checkUser_modal").modal("hide");
}

//加载筛选人员列表
function checkUser_getList(pageNo){
    $("input[name='checkUser_checkAll']").iCheck("uncheck");
    var content = $("#checkUser_content").val();
    var departmentId = $("#checkUser_department_id").val();
    var postId = $("#checkUser_post").val();
    var userTags = $("#checkUser_tags").val();
    var params = {"content":content,"departmentId":departmentId,"postId":postId,"userTags":userTags,"userType":checkUserType,"pageNo":pageNo};
    $.post(checkUserList_url,params,function(data){
        var checkUserListStr = "";
        var userPage = data.userPage;
        if(userPage.rows.length > 0){
            var pageNo = userPage.pageNo;
            var pageSize = userPage.pageSize;
            var totalPages = userPage.totalPages;
            var checkNum = 0;
            $.each(userPage.rows,function(i,user){
                var indexNo = (pageNo-1)*pageSize+(i+1);
                var userId = user.userId;
                var loginName = user.loginName;
                var userName = user.userName;
                var userJobNumber = user.userJobNumber;
                var departmentName = user.departmentName;
                var postName = user.postName;
                checkUserListStr+='<tr><td><input class="checkbox checkUser" type="checkbox" name="checkUser_checkUser" ';
                var checkUserArray = $("#checkUser_userIds").val().split(",");
                if($.inArray(userId,checkUserArray)>=0){
                    ++checkNum;
                    checkUserListStr+='checked="checked" ';
                }
                checkUserListStr+='value="'+userId+'" userName="'+userName+'"></td><td>'+indexNo+'</td>';
                checkUserListStr+='<td>'+loginName+'</td>';
                checkUserListStr+='<td>'+userName+'</td>';
                checkUserListStr+='<td>'+userJobNumber+'</td>';
                checkUserListStr+='<td>'+departmentName+'</td>';
                checkUserListStr+='<td>'+postName+'</td>';
                checkUserListStr+='</tr>';
            });
            $("#checkUser_userList").html(checkUserListStr);
            var checkBoxNum = $("input[name='checkUser_checkUser']").length;
            if(checkNum==checkBoxNum){
                $("input[name='checkUser_checkAll']").iCheck("check");
            }
            if(totalPages>1){
                checkUser_pageLimit(pageNo,totalPages,"checkUser_pageBar");
            }
            $("input[name='checkUser_checkUser']").iCheck({
                checkboxClass: "icheckbox_minimal-blue",
                radioClass: "iradio_minimal-blue",
                increaseArea: "20%"
            });
            $("input[name='checkUser_checkUser']").on("ifClicked", function(event){
                var checkNum = $("input[name='checkUser_checkUser']:checked").length;
                if((checkNum+1)==checkBoxNum){
                    $("input[name='checkUser_checkAll']").iCheck("check");
                }
                var userId = $(this).val();
                if(!$(this).prop("checked")){
                    var userName = $(this).attr("userName");
                    var checkUserArray = $("#checkUser_userIds").val().split(",");
                    if($.inArray(userId,checkUserArray) < 0){
                        checkUserArray.push(userId);
                        var userName = $(this).attr("userName");
                        var checkUserStr='<span class="btn btn-default btn-xs" id="checkUser_'+userId+'" style="margin: 0px 5px 5px 0px;">'+userName+'<span aria-hidden="true" onclick=removeCheckUser("'+userId+'")>&nbsp;&times;</span></span>';
                        $("#checkUser_userIds").val(array_remove("",checkUserArray));
                        $("#checkUser_area").append(checkUserStr);
                    }
                }else{
                    $("input[name='checkUser_checkAll']").iCheck("uncheck");
                    removeCheckUser(userId);
                }
            });
        }else{
            $("#checkUser_pageBar").html("");
            checkUserListStr='<tr><td colspan="7" style="vertical-align:middle;"><h4 class="text-center"><small>没有找到相关数据</small></h4></td></tr>';
            $("#checkUser_userList").html(checkUserListStr);
        }
    })
}
//移除已选人员
function removeCheckUser(id){
    $("#checkUser_"+id).remove();
    var checkUserArray = $("#checkUser_userIds").val().split(",");
    $("#checkUser_userIds").val(array_remove(id,checkUserArray));
    $("input[name='checkUser_checkUser'][value='"+id+"']").iCheck("uncheck");
    $("input[name='checkUser_checkAll']").iCheck("uncheck");
}
//数组移除某一项
function array_remove(value,array){
    var newArray = new Array();
    $.each(array,function(i,item){
        if(item != value){
            newArray.push(item);
        }
    })
    return newArray;
}
//数组去除重复值
function array_unique(array){
    array = array || [];
    var a = {};
    var len = array.length;
    for (var i=0; i<len;i++){
        var v = array[i];
        if (typeof(a[v]) == 'undefined'){
            a[v] = 1;
        }
    };
    array.length=0;
    for (var x in a){
        array[array.length] = x;
    }
    return array;
}
//分页设置
function checkUser_pageLimit(currentPage,totalPages,pageBarId) {
    var options = {
        currentPage: currentPage,
        totalPages: totalPages,
        numberOfPages: 5,
        bootstrapMajorVersion: 3,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "尾页";
                case "page":
                    return page;
            }
        },
        tooltipTitles: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "尾页";
                case "page":
                    return "第"+page+"页";
            }
        },
        onPageClicked: function (e, originalEvent, type, pageNo) {
            checkUser_getList(pageNo);
        }
    }
    $("#"+pageBarId).bootstrapPaginator(options);
    $("#"+pageBarId).addClass("pagination-sm");
}